{{>licenseInfo}}

package {{package}};

import {{invokerPackage}}.ApiResponse;
import com.amazon.SellingPartnerAPIAA.LWAAuthorizationCredentials;
import org.jeasy.random.EasyRandom;
import org.jeasy.random.EasyRandomParameters;
import org.threeten.bp.LocalDate;
import org.threeten.bp.OffsetDateTime;
{{#imports}}import {{import}};
{{/imports}}
import org.junit.jupiter.api.Test;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.*;
import java.util.stream.Collectors;

import static org.junit.jupiter.api.Assertions.*;

public class {{classname}}Test {

    private static final String endpoint = "http://localhost:3000";
    private static final String authEndpoint = "http://localhost:3000/auth/o2/token";
    private static final LWAAuthorizationCredentials credentials = LWAAuthorizationCredentials.builder()
        .clientId("clientId")
        .clientSecret("clientSecret")
        .refreshToken("refreshToken")
        .endpoint(authEndpoint)
        .build();

    private final {{classname}} api = new {{classname}}.Builder()
        .lwaAuthorizationCredentials(credentials)
        .endpoint(endpoint)
        .build();

    private final EasyRandom easyRandom = new EasyRandom(
        new EasyRandomParameters().randomize(OffsetDateTime.class, OffsetDateTime::now)
                .randomize(LocalDate.class, LocalDate::now)
                .collectionSizeRange(1, 2)
    );

{{#operations}}{{#operation}}
    @Test
    public void {{operationId}}Test() throws Exception {
        instructBackendMock("{{operationId}}", "{{responses.0.code}}");
        {{#allParams}}{{#required}}
        {{{dataType}}} {{paramName}} = {{#isListContainer}}easyRandom.objects({{baseType}}.class, 2).collect(Collectors.toList()){{/isListContainer}}{{^isListContainer}}easyRandom.nextObject({{{dataType}}}.class){{/isListContainer}};
        {{/required}}{{/allParams}}

        {{#returnType}}ApiResponse<{{{returnType}}}> response = {{/returnType}}api.{{operationId}}WithHttpInfo({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}});

        {{#returnType}}
        assertEquals({{responses.0.code}}, response.getStatusCode());
        assertValidResponsePayload({{responses.0.code}}, response.getData());
        {{/returnType}}
    }

{{/operation}}{{/operations}}

    private void instructBackendMock(String response, String code) throws Exception {
        HttpRequest request = HttpRequest.newBuilder()
              .uri(new URI(endpoint + "/response/" + response + "/code/" + code))
              .POST(HttpRequest.BodyPublishers.noBody())
              .build();

        HttpClient.newHttpClient().send(request, BodyHandlers.discarding());
    }

    private static void assertValidResponsePayload(int statusCode, Object body) {
        if(statusCode != 204) assertNotNull(body);
    }
}
